import 'package:todo_app/constants/Screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

typedef Widget OverlayWidgetBuilder(BuildContext context, OverlaySupportState state);

OverlayEntry showOverlay({
  required OverlayWidgetBuilder builder,
}) {
  OverlaySupportState? supportState = OverlaySupport.of(_keyFinder.currentContext!);
  OverlayEntry entry = OverlayEntry(builder: (_)=> DefaultTextStyle(style: TextStyle(
    fontSize: Screen.sizeByDesign(14),
    color: Colors.white,
    decoration: TextDecoration.none,
    fontWeight: FontWeight.normal
  ), child: 
    builder(_, supportState!)
  ));
  supportState!.overlay.insert(entry);
  return entry;
}

class OverlaySupport extends StatefulWidget {
  OverlaySupport({Key? key, required this.child, required this.navigatorKey }) : super(key: key);

  final Widget child;

  final GlobalKey<NavigatorState> navigatorKey;

  static OverlaySupportState? of(BuildContext context) {
    return context.findRootAncestorStateOfType<OverlaySupportState>();
  }

  @override
  OverlaySupportState createState() => OverlaySupportState();
}

class OverlaySupportState extends State<OverlaySupport> {

  List<OverlayEntry> entrys = [];

  OverlayState get overlay {
    NavigatorState? navigator;

    if(widget.navigatorKey.currentState != null) {
      return widget.navigatorKey.currentState!.overlay!;
    }

    void visitor(Element element) {
      if (navigator != null) return;
      if (element.widget is Navigator) {
        navigator = element.findRootAncestorStateOfType<NavigatorState>();
      } else {
        element.visitChildElements(visitor);
      }
    }
    context.visitChildElements(visitor);
    return navigator!.overlay!;
  }

  @override
  Widget build(BuildContext context) {
    return _OverlayFinder(
        key: _keyFinder,
        child: widget.child
    );
  }
}

final GlobalKey<_OverlayFinderState> _keyFinder = GlobalKey(debugLabel: 'overlay_support');
/// Used to find the [Overlay] in decedents tree.
class _OverlayFinder extends StatefulWidget {
  final Widget child;

  const _OverlayFinder({Key? key, required this.child}) : super(key: key);

  @override
  _OverlayFinderState createState() => _OverlayFinderState();
}

class _OverlayFinderState extends State<_OverlayFinder> {
  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}
